package cn.iocoder.yudao.module.system.controller.admin.userbehavior;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
// 移除OperateLog导入，项目使用LogRecord注解
import cn.iocoder.yudao.module.system.dal.dataobject.userbehavior.UserBehaviorDetailDO;
import cn.iocoder.yudao.module.system.dal.dataobject.userbehavior.UserBehaviorStatsDO;
import cn.iocoder.yudao.module.system.dal.dataobject.userbehavior.UserFeaturePathDO;
import cn.iocoder.yudao.module.system.service.userbehavior.UserBehaviorStatsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;

/**
 * 用户行为统计 Controller
 *
 * @author 系统开发团队
 */
@Tag(name = "管理后台 - 用户行为统计")
@RestController
@RequestMapping("/system/user-behavior-stats")
@Validated
public class UserBehaviorStatsController {

    @Resource
    private UserBehaviorStatsService userBehaviorStatsService;

    // ========== 行为统计数据查询 ==========

    @GetMapping("/page")
    @Operation(summary = "获得用户行为统计分页")
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:query')")
    public CommonResult<PageResult<UserBehaviorStatsDO>> getUserBehaviorStatsPage(
            @RequestParam(value = "startDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam(value = "endDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate,
            @RequestParam(value = "statType", required = false) Integer statType,
            @RequestParam(value = "calculationStatus", required = false) Integer calculationStatus,
            @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        PageResult<UserBehaviorStatsDO> pageResult = userBehaviorStatsService.getUserBehaviorStatsPage(
                startDate, endDate, statType, calculationStatus, pageNo, pageSize);
        return success(pageResult);
    }

    @GetMapping("/overview")
    @Operation(summary = "获得用户行为统计概览")
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:query')")
    public CommonResult<Map<String, Object>> getUserBehaviorStatsOverview(
            @RequestParam(value = "startDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam(value = "endDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        Map<String, Object> overview = userBehaviorStatsService.getUserBehaviorStatsOverview(startDate, endDate);
        return success(overview);
    }

    @GetMapping("/trend")
    @Operation(summary = "获得用户行为趋势")
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:query')")
    public CommonResult<List<UserBehaviorStatsDO>> getUserBehaviorTrend(
            @RequestParam(value = "startDate") @DateTimeFormat(pattern = "yyyy-MM-dd") @NotNull LocalDate startDate,
            @RequestParam(value = "endDate") @DateTimeFormat(pattern = "yyyy-MM-dd") @NotNull LocalDate endDate,
            @RequestParam(value = "statType", defaultValue = "1") Integer statType) {
        List<UserBehaviorStatsDO> trend = userBehaviorStatsService.getUserBehaviorTrend(startDate, endDate, statType);
        return success(trend);
    }

    @GetMapping("/detail")
    @Operation(summary = "获得用户行为统计详情")
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:query')")
    public CommonResult<UserBehaviorStatsDO> getUserBehaviorStatsDetail(
            @RequestParam("statDate") @DateTimeFormat(pattern = "yyyy-MM-dd") @NotNull LocalDate statDate,
            @RequestParam(value = "statType", defaultValue = "1") Integer statType) {
        UserBehaviorStatsDO detail = userBehaviorStatsService.getUserBehaviorStatsDetail(statDate, statType);
        return success(detail);
    }

    @GetMapping("/latest")
    @Operation(summary = "获得最新的用户行为统计")
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:query')")
    public CommonResult<List<UserBehaviorStatsDO>> getLatestUserBehaviorStats(
            @RequestParam(value = "statType", defaultValue = "1") Integer statType,
            @RequestParam(value = "limit", defaultValue = "7") Integer limit) {
        List<UserBehaviorStatsDO> latest = userBehaviorStatsService.getLatestUserBehaviorStats(statType, limit);
        return success(latest);
    }

    // ========== 用户行为详情管理 ==========

    @PostMapping("/behavior-detail")
    @Operation(summary = "记录用户行为详情")
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:create')")
    public CommonResult<UserBehaviorDetailDO> recordUserBehaviorDetail(@Valid @RequestBody UserBehaviorDetailDO behaviorDetail) {
        UserBehaviorDetailDO result = userBehaviorStatsService.recordUserBehaviorDetail(behaviorDetail);
        return success(result);
    }

    @PostMapping("/behavior-detail/batch")
    @Operation(summary = "批量记录用户行为详情")
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:create')")
    public CommonResult<Boolean> batchRecordUserBehaviorDetail(@Valid @RequestBody List<UserBehaviorDetailDO> behaviorDetails) {
        boolean result = userBehaviorStatsService.batchRecordUserBehaviorDetail(behaviorDetails);
        return success(result);
    }

    @GetMapping("/behavior-detail/page")
    @Operation(summary = "获得用户行为详情分页")
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:query')")
    public CommonResult<PageResult<UserBehaviorDetailDO>> getUserBehaviorDetailPage(
            @RequestParam(value = "userId", required = false) Long userId,
            @RequestParam(value = "behaviorType", required = false) Integer behaviorType,
            @RequestParam(value = "userType", required = false) Integer userType,
            @RequestParam(value = "startTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(value = "endTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime,
            @RequestParam(value = "sessionId", required = false) String sessionId,
            @RequestParam(value = "behaviorResult", required = false) Integer behaviorResult,
            @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        PageResult<UserBehaviorDetailDO> pageResult = userBehaviorStatsService.getUserBehaviorDetailPage(
                userId, behaviorType, userType, startTime, endTime, sessionId, behaviorResult, pageNo, pageSize);
        return success(pageResult);
    }

    @GetMapping("/behavior-detail/user/{userId}")
    @Operation(summary = "获得用户行为详情")
    @Parameter(name = "userId", description = "用户ID", required = true)
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:query')")
    public CommonResult<List<UserBehaviorDetailDO>> getUserBehaviorDetails(
            @PathVariable("userId") Long userId,
            @RequestParam(value = "startTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(value = "endTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        List<UserBehaviorDetailDO> details = userBehaviorStatsService.getUserBehaviorDetails(userId, startTime, endTime);
        return success(details);
    }

    @GetMapping("/behavior-detail/recent/{userId}")
    @Operation(summary = "获得用户最近行为")
    @Parameter(name = "userId", description = "用户ID", required = true)
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:query')")
    public CommonResult<List<UserBehaviorDetailDO>> getUserRecentBehaviors(
            @PathVariable("userId") Long userId,
            @RequestParam(value = "limit", defaultValue = "10") Integer limit) {
        List<UserBehaviorDetailDO> behaviors = userBehaviorStatsService.getUserRecentBehaviors(userId, limit);
        return success(behaviors);
    }

    @GetMapping("/behavior-detail/popular-features")
    @Operation(summary = "获得热门功能")
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:query')")
    public CommonResult<List<Map<String, Object>>> getPopularFeatures(
            @RequestParam(value = "startTime") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @NotNull LocalDateTime startTime,
            @RequestParam(value = "endTime") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @NotNull LocalDateTime endTime,
            @RequestParam(value = "limit", defaultValue = "10") Integer limit) {
        List<Map<String, Object>> features = userBehaviorStatsService.getPopularFeatures(startTime, endTime, limit);
        return success(features);
    }

    // ========== 用户功能路径管理 ==========

    @PostMapping("/feature-path")
    @Operation(summary = "记录用户功能路径")
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:create')")
    public CommonResult<UserFeaturePathDO> recordUserFeaturePath(@Valid @RequestBody UserFeaturePathDO featurePath) {
        UserFeaturePathDO result = userBehaviorStatsService.recordUserFeaturePath(featurePath);
        return success(result);
    }

    @PutMapping("/feature-path")
    @Operation(summary = "更新用户功能路径")
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:update')")
    public CommonResult<Boolean> updateUserFeaturePath(@Valid @RequestBody UserFeaturePathDO featurePath) {
        boolean result = userBehaviorStatsService.updateUserFeaturePath(featurePath);
        return success(result);
    }

    @GetMapping("/feature-path/page")
    @Operation(summary = "获得用户功能路径分页")
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:query')")
    public CommonResult<PageResult<UserFeaturePathDO>> getUserFeaturePathPage(
            @RequestParam(value = "userId", required = false) Long userId,
            @RequestParam(value = "userType", required = false) Integer userType,
            @RequestParam(value = "completionStatus", required = false) Integer completionStatus,
            @RequestParam(value = "conversionAchieved", required = false) Boolean conversionAchieved,
            @RequestParam(value = "startTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(value = "endTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime,
            @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        PageResult<UserFeaturePathDO> pageResult = userBehaviorStatsService.getUserFeaturePathPage(
                userId, userType, completionStatus, conversionAchieved, startTime, endTime, pageNo, pageSize);
        return success(pageResult);
    }

    @GetMapping("/feature-path/user/{userId}")
    @Operation(summary = "获得用户功能路径")
    @Parameter(name = "userId", description = "用户ID", required = true)
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:query')")
    public CommonResult<List<UserFeaturePathDO>> getUserFeaturePaths(
            @PathVariable("userId") Long userId,
            @RequestParam(value = "startTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(value = "endTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        List<UserFeaturePathDO> paths = userBehaviorStatsService.getUserFeaturePaths(userId, startTime, endTime);
        return success(paths);
    }

    @GetMapping("/feature-path/recent/{userId}")
    @Operation(summary = "获得用户最近路径")
    @Parameter(name = "userId", description = "用户ID", required = true)
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:query')")
    public CommonResult<List<UserFeaturePathDO>> getUserRecentPaths(
            @PathVariable("userId") Long userId,
            @RequestParam(value = "limit", defaultValue = "10") Integer limit) {
        List<UserFeaturePathDO> paths = userBehaviorStatsService.getUserRecentPaths(userId, limit);
        return success(paths);
    }

    @GetMapping("/feature-path/popular-paths")
    @Operation(summary = "获得热门路径")
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:query')")
    public CommonResult<List<Map<String, Object>>> getPopularPaths(
            @RequestParam(value = "startTime") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @NotNull LocalDateTime startTime,
            @RequestParam(value = "endTime") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @NotNull LocalDateTime endTime,
            @RequestParam(value = "limit", defaultValue = "10") Integer limit) {
        List<Map<String, Object>> paths = userBehaviorStatsService.getPopularPaths(startTime, endTime, limit);
        return success(paths);
    }

    @GetMapping("/feature-path/high-conversion")
    @Operation(summary = "获得高转化路径")
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:query')")
    public CommonResult<List<UserFeaturePathDO>> getHighConversionPaths(
            @RequestParam(value = "startTime") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @NotNull LocalDateTime startTime,
            @RequestParam(value = "endTime") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @NotNull LocalDateTime endTime,
            @RequestParam(value = "minConversionRate", defaultValue = "0.1") BigDecimal minConversionRate) {
        List<UserFeaturePathDO> paths = userBehaviorStatsService.getHighConversionPaths(startTime, endTime, minConversionRate);
        return success(paths);
    }

    // ========== 行为数据分析 ==========

    @GetMapping("/analysis/feature-usage-pattern")
    @Operation(summary = "分析功能使用模式")
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:query')")
    public CommonResult<Map<String, Object>> analyzeFeatureUsagePattern(
            @RequestParam(value = "startDate") @DateTimeFormat(pattern = "yyyy-MM-dd") @NotNull LocalDate startDate,
            @RequestParam(value = "endDate") @DateTimeFormat(pattern = "yyyy-MM-dd") @NotNull LocalDate endDate) {
        Map<String, Object> analysis = userBehaviorStatsService.analyzeFeatureUsagePattern(startDate, endDate);
        return success(analysis);
    }

    @GetMapping("/analysis/conversion-funnel")
    @Operation(summary = "分析用户转化漏斗")
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:query')")
    public CommonResult<Map<String, Object>> analyzeConversionFunnel(
            @RequestParam(value = "startDate") @DateTimeFormat(pattern = "yyyy-MM-dd") @NotNull LocalDate startDate,
            @RequestParam(value = "endDate") @DateTimeFormat(pattern = "yyyy-MM-dd") @NotNull LocalDate endDate) {
        Map<String, Object> analysis = userBehaviorStatsService.analyzeConversionFunnel(startDate, endDate);
        return success(analysis);
    }

    @GetMapping("/analysis/user-path-pattern")
    @Operation(summary = "分析用户路径模式")
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:query')")
    public CommonResult<Map<String, Object>> analyzeUserPathPattern(
            @RequestParam(value = "startTime") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @NotNull LocalDateTime startTime,
            @RequestParam(value = "endTime") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @NotNull LocalDateTime endTime) {
        Map<String, Object> analysis = userBehaviorStatsService.analyzeUserPathPattern(startTime, endTime);
        return success(analysis);
    }

    @GetMapping("/analysis/user-engagement")
    @Operation(summary = "分析用户参与度")
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:query')")
    public CommonResult<Map<String, Object>> analyzeUserEngagement(
            @RequestParam(value = "startTime") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @NotNull LocalDateTime startTime,
            @RequestParam(value = "endTime") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @NotNull LocalDateTime endTime) {
        Map<String, Object> analysis = userBehaviorStatsService.analyzeUserEngagement(startTime, endTime);
        return success(analysis);
    }

    @GetMapping("/analysis/feature-drop-off")
    @Operation(summary = "分析功能流失点")
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:query')")
    public CommonResult<Map<String, Object>> analyzeFeatureDropOff(
            @RequestParam(value = "startTime") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @NotNull LocalDateTime startTime,
            @RequestParam(value = "endTime") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @NotNull LocalDateTime endTime) {
        Map<String, Object> analysis = userBehaviorStatsService.analyzeFeatureDropOff(startTime, endTime);
        return success(analysis);
    }

    // ========== 统计计算管理 ==========

    @PostMapping("/calculate")
    @Operation(summary = "计算用户行为统计")
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:create')")
    public CommonResult<Boolean> calculateUserBehaviorStats(
            @RequestParam("statDate") @DateTimeFormat(pattern = "yyyy-MM-dd") @NotNull LocalDate statDate) {
        boolean result = userBehaviorStatsService.calculateUserBehaviorStats(statDate);
        return success(result);
    }

    @PostMapping("/batch-calculate")
    @Operation(summary = "批量计算用户行为统计")
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:create')")
    public CommonResult<Boolean> batchCalculateUserBehaviorStats(
            @RequestParam("startDate") @DateTimeFormat(pattern = "yyyy-MM-dd") @NotNull LocalDate startDate,
            @RequestParam("endDate") @DateTimeFormat(pattern = "yyyy-MM-dd") @NotNull LocalDate endDate) {
        boolean result = userBehaviorStatsService.batchCalculateUserBehaviorStats(startDate, endDate);
        return success(result);
    }

    @PostMapping("/recalculate")
    @Operation(summary = "重新计算用户行为统计")
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:update')")
    public CommonResult<Boolean> recalculateUserBehaviorStats(
            @RequestParam("statDate") @DateTimeFormat(pattern = "yyyy-MM-dd") @NotNull LocalDate statDate) {
        boolean result = userBehaviorStatsService.recalculateUserBehaviorStats(statDate);
        return success(result);
    }

    @GetMapping("/calculation-progress")
    @Operation(summary = "获得计算进度")
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:query')")
    public CommonResult<Map<String, Object>> getCalculationProgress(
            @RequestParam(value = "startDate") @DateTimeFormat(pattern = "yyyy-MM-dd") @NotNull LocalDate startDate,
            @RequestParam(value = "endDate") @DateTimeFormat(pattern = "yyyy-MM-dd") @NotNull LocalDate endDate) {
        Map<String, Object> progress = userBehaviorStatsService.getCalculationProgress(startDate, endDate);
        return success(progress);
    }

    @GetMapping("/data-integrity")
    @Operation(summary = "检查数据完整性")
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:query')")
    public CommonResult<Map<String, Object>> checkDataIntegrity(
            @RequestParam(value = "startDate") @DateTimeFormat(pattern = "yyyy-MM-dd") @NotNull LocalDate startDate,
            @RequestParam(value = "endDate") @DateTimeFormat(pattern = "yyyy-MM-dd") @NotNull LocalDate endDate) {
        Map<String, Object> integrity = userBehaviorStatsService.checkDataIntegrity(startDate, endDate);
        return success(integrity);
    }

    // ========== 数据管理 ==========

    @DeleteMapping("/expired-stats")
    @Operation(summary = "删除过期的行为统计数据")
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:delete')")
    public CommonResult<Integer> deleteExpiredBehaviorStats(
            @RequestParam("beforeDate") @DateTimeFormat(pattern = "yyyy-MM-dd") @NotNull LocalDate beforeDate) {
        int count = userBehaviorStatsService.deleteExpiredBehaviorStats(beforeDate);
        return success(count);
    }

    @DeleteMapping("/expired-details")
    @Operation(summary = "删除过期的行为详情数据")
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:delete')")
    public CommonResult<Integer> deleteExpiredBehaviorDetails(
            @RequestParam("beforeTime") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @NotNull LocalDateTime beforeTime) {
        int count = userBehaviorStatsService.deleteExpiredBehaviorDetails(beforeTime);
        return success(count);
    }

    @DeleteMapping("/expired-paths")
    @Operation(summary = "删除过期的功能路径数据")
    @PreAuthorize("@ss.hasPermission('system:user-behavior-stats:delete')")
    public CommonResult<Integer> deleteExpiredFeaturePaths(
            @RequestParam("beforeTime") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @NotNull LocalDateTime beforeTime) {
        int count = userBehaviorStatsService.deleteExpiredFeaturePaths(beforeTime);
        return success(count);
    }
}